/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import Navigation from "../../../custom/Navigation";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import {DATE_DATA} from "../../../res/json/monthsJson";
import StarView from "../../../custom/StarView";
import SlideMenu from "../../../menu/SlideMenu";
import GoodsIsBuyPage from "../../common/GoodsIsBuyPage";

export default class BasicInfoPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userData: this.props.userData,
            sponsorData: '',
            swap_amount: '',
            dataSourceLength: []
        };

        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        let userData = this.state.userData;
        this.getUserInfo(userData.parent_id);
        this.onNewUserOrder(userData.user_id);
        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                this.setState({swap_amount: JSON.parse(result).swap_amount});
            })
    }

    /*
    *网络请求
    * 获取用户详细信息
    */
    getUserInfo(userID) {
        if (!userID) {
            return
        }

        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'user_id=' + userID)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    this.setState({sponsorData: result.data});
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error)
            })
    }


    /**
     * 获取摸个时间段摸个用户的订单数据
     * */
    onNewUserOrder(user_id) {
        CommonUtils.showLoading();



        let year = DATE_DATA.year;
        let startMonth = DATE_DATA.month;
        let startYear = year;

        if (startMonth <= 0) {
            startYear = year - 1;
            startMonth = 12 + startMonth
        }

        let endTime = year + '-' + startMonth + '-' + '31';
        let startTime = startYear + '-' + startMonth + '-' + '01';
        let _params = '&action_time=' + startTime + '&end_time=' + endTime + '&user_id=' + user_id;

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'newUserOrder?', _params)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    this.setState({dataSourceLength: result.data.length})
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                console.log(error);
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });
    }

    // /*
    // *网络请求
    // * 搜索推荐人信息
    // */
    // getSponsorInfo(randId) {
    // 	this.iparNetwork.getRequest(SERVER_TYPE.admin + 'searchSponsor?', 'keywords=' + randId)//rand_id
    // 		.then((result) => {
    // 			if (result.code === 200) {
    // 				this.setState({sponsorData: result.data});
    //
    // 			}
    // 		})
    // 		.catch((error) => {
    // 			console.log(error)
    // 		})
    // }


    /*用户信息Text*/
    getUserTv(arry) {
        let arrTv = [];
        for (let i = 0; i < arry.length; i++) {
            arrTv.push(
                <Text style={[{marginTop: 16}, StyleUtils.smallFont]}>{arry[i]}</Text>
            )
        }
        return arrTv
    }

    /*splitTpe*/
    getSales(sales) {
        if (!sales) return '';
        let splitTpe = [];
        let split = sales.split(',');
        for (let i = 0; i < split.length; i++) {
            switch (split[i]) {
                case 'bjp':
                    splitTpe.push(I18n.t('default.healthFood'));//Health food
                    break;
                case 'grh':
                    splitTpe.push(I18n.t('default.personalCare'));//Personal care
                    break;
                case 'hzp':
                    splitTpe.push(I18n.t('default.skinCare'));//Skin care
                    break;
                case 'nxh':
                    splitTpe.push(I18n.t('default.suncellaFemale'));//Suncella female intimate care
                    break;
                case 'dzc':
                    splitTpe.push(I18n.t('default.electrronics'));//Electrronics
                    break;
            }
        }

        return splitTpe;
    }

    // /**
    //  * Marketing plan
    //  * */
    // getBusiness(business) {
    //     let busType;
    //     switch (business.rank) {
    //         case 1:
    //             busType = I18n.t('default.vip');
    //             break;
    //         case 2:
    //             busType = I18n.t('default.rocketPlan');
    //             break;
    //         case 3:
    //             busType = I18n.t('default.GoodToProgram');
    //             break;
    //         case 4:
    //             busType = I18n.t('default.GrowPlan');
    //             break
    //     }
    //
    //     return busType;
    //
    // }

    // /**
    //  * 用户level类型
    //  * */
    // getLevelType(level) {
    //     let t_lavel = 'null';
    //
    //     switch (level) {
    //         case 0:
    //         case 1:
    //             t_lavel = 'VIP';
    //             break;
    //         case 2:
    //             t_lavel = 'Star VIP';
    //             break;
    //         case 3:
    //             t_lavel = 'CIBM';
    //             break;
    //         case 4:
    //             t_lavel = 'IBM';
    //             break;
    //         case 5:
    //             t_lavel = 'S-IBM';
    //             break;
    //         case 6:
    //             t_lavel = 'G-IBM';
    //             break;
    //         case 7:
    //             t_lavel = 'P-IBM';
    //             break;
    //         case 8:
    //             t_lavel = 'L-Bronze';
    //             break;
    //         case 9:
    //             t_lavel = 'L-Silver';
    //             break;
    //         case 10:
    //             t_lavel = 'L-Gold';
    //             break;
    //         case 11:
    //             t_lavel = 'Star-gold';
    //             break;
    //         case 12:
    //             t_lavel = 'DS-gold';
    //             break;
    //         case 13:
    //             t_lavel = 'TS-gold';
    //             break;
    //         case 14:
    //             t_lavel = 'S-diamond';
    //             break;
    //         case 15:
    //             t_lavel = 'DS-diamond';
    //             break;
    //     }
    //     return t_lavel;
    // }


    getAverageScoreValue(value) {
        let _value = 0.0;
        if (value > 0 && value < 4) {//1~3
            _value = 0.3
        } else if (value > 3 && value < 6) {//4~5
            _value = 0.5
        } else if (value > 5 && value < 9) {//6~8
            _value = 0.8
        } else if (value > 8) {//8<
            _value = 0.9
        }

        return _value;
    }


    onClick(type) {
        let userData = this.state.userData;
        let _component = null;
        let _params = {};
        switch (type) {
            case 'is_reg_pack'://注册包
                _component = GoodsIsBuyPage;
                _params = {
                    goods_id: userData.user_rank ? userData.user_rank.reg_goods_id : '',
                    title: I18n.t('b.regsitrationPack'),
                };
                DeviceEventEmitter.emit('upDateUserData', userData);
                break;
            case 'is_buy':
                _component = GoodsIsBuyPage;
                _params = {
                    goods_id: userData.user_rank ? userData.user_rank.sell_goods_id : '',
                    title: I18n.t('default.ibmStarterPack'),
                };
                DeviceEventEmitter.emit('upDateUserData', userData);
                break;
            case 'is_prereg':
                DeviceEventEmitter.emit('goToPage', 0);
                new CommonUtils().popToRoute(this, 'SlideMenu');
                break;
        }

        if (_component) {
            this.props.navigator.push({
                component: _component,
                name: _component + '',
                params: _params,
            });
        }

    }

    render() {


        let userUi;
        let userData = this.state.userData;//获取用户详细信息

        let sponsorData = this.state.sponsorData;//搜索推荐人信息

        if (userData !== '') {
            let business = userData;
            let contact = sponsorData;

            userUi = <View>
                {/*{ViewUtils.gitUserInformationTv(I18n.t('default.marketingPlan'),   business.rank ? this.getBusiness(business) : null, '', () => {*/}
                {/*})}*/}
                {ViewUtils.gitUserInformationTv(I18n.t('default.currentLevel'),
                    //this.getLevelType(business.level)
                    userData.user_level ? userData.user_level.level_name : '', '', () => {
                    })}
                {/*{ViewUtils.gitUserInformationTv(I18n.t('default.activity'), 'sss', '', () => {*/}
                {/*})}*/}
                <TouchableOpacity
                    activeOpacity={0.5}
                    style={[StyleUtils.tvBox, StyleUtils.center]}
                >
                    <View style={StyleUtils.flex}>
                        <Text
                            numberOfLines={2}
                            style={[StyleUtils.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.activity')}</Text>

                        <StarView
                            style={{marginTop: 8}}
                            num={3}
                        />
                    </View>

                </TouchableOpacity>

                {ViewUtils.gitUserInformationTv(I18n.t('default.averageScore'), this.getAverageScoreValue(this.state.dataSourceLength), null, () => {
                })}
                {ViewUtils.gitUserInformationTv(I18n.t('default.nickName'), userData.nick_name, '', () => {
                })}
                {ViewUtils.gitUserInformationTv(I18n.t('default.myIparId'), business.rand_id ? business.rand_id : null, '', () => {
                })}
                {ViewUtils.gitUserInformationTv(I18n.t('default.Key'), business.code ? business.code : null, '', () => {
                })}

                <Text
                    style={[styles.titleTv, StyleUtils.smallFont, {textAlign: 'left'}]}>{I18n.t('default.sponsorInfo')}</Text>
                <Text
                    style={[styles.marginTop, StyleUtils.smallFont, {textAlign: 'left'}]}>{contact ? contact.first_name + ' ' + contact.last_name : null}</Text>
                <Text
                    style={[styles.marginTop, StyleUtils.smallFont, {textAlign: 'left'}]}>{sponsorData ? sponsorData.area_code + ' ' + sponsorData.mobile : null}</Text>
                <Text
                    style={[styles.marginTop, StyleUtils.smallFont, {textAlign: 'left'}]}>{contact && contact.email ? contact.email : null}</Text>
                <View style={[StyleUtils.lineStyle, StyleUtils.smallFont]}/>


                {ViewUtils.gitUserInformationTv(I18n.t('b.regsitrationPack'), userData.is_reg_pack === 1 ? (I18n.t('default.activated') + '\n' + (userData.reg_pack_time || '')) : I18n.t('default.notActivated'),
                    require('../../../res/images/ic_right_more.png'), userData.is_reg_pack !== 1 ? () => this.onClick('is_reg_pack') : null)}

                {ViewUtils.gitUserInformationTv(I18n.t('default.ibmStarterPack'), userData.is_buy === 1 ? (I18n.t('default.activated') + '\n' + (userData.buy_time || '')) : I18n.t('default.notActivated'),
                    require('../../../res/images/ic_right_more.png'), userData.is_buy !== 1 ? () => this.onClick('is_buy') : null)}

                {ViewUtils.gitUserInformationTv(I18n.t('b.volumeThreshold'), userData.is_prereg === 1 ? I18n.t('default.activated') : I18n.t('default.notActivated'),
                    require('../../../res/images/ic_right_more.png'), () => this.startNewShop(userData))}

                {/*选择子账号*/}
                {/*{ViewUtils.gitUserInformationTv(I18n.t('b.defaultBusiness'), userData.rand_id,*/}
                {/*require('../../../res/images/ic_right_more.png'), () => this.startNewShop(userData))}*/}

                {ViewUtils.getButton(I18n.t('default.startShoppingBtn'), () => this.startNewShop(userData), {marginBottom: 34})}

            </View>
        }


        return (

            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}

                />

                <ScrollView style={StyleUtils.flex}>
                    <View style={{paddingLeft: 16, paddingRight: 16}}>
                        {ViewUtils.getTitleView(this.props.title || I18n.t('default.myBusiness'), I18n.t('default.myBusinessNot'))}
                        {userUi}

                    </View>
                </ScrollView>
            </View>
        );
    }

    startNewShop(userData) {
        if (userData.user_id == userData.main_user_id) {
            DeviceEventEmitter.emit('toast', I18n.t('b.selectDefaultBusiness'))
        } else {
            CommonUtils.saveUserInfo(userData);
            const {navigator} = this.props;
            navigator.resetTo({
                component: SlideMenu,
                name: 'SlideMenu',
                params: {
                    ...this.props,
                }
            });

        }
    }

}
const styles = StyleSheet.create({
    marginTop: {
        marginTop: 16
    },
    titleTv: {
        marginTop: 16,
        fontSize: 18,
        color: 'black',
        textAlign: 'left'
    }
});